// Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::{fmt::Display, str::FromStr};

use serde::{Deserialize, Serialize};

use crate::{Arch, Pkg, PkgParseError, PkgSpec};

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct PkgWithArch {
    pub pkg: Pkg,
    pub arch: Arch,
}

#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum PkgWithArchParseError {
    #[error("no arch")]
    NoArch,
    #[error("bad pkg")]
    BadPkg(#[from] PkgParseError),
    #[error("bad arch")]
    BadArch,
}

impl Serialize for PkgWithArch {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer
    {
        serializer.serialize_str(&self.to_string())
    }
}

impl<'de> Deserialize<'de> for PkgWithArch {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>
    {
        struct StringVisitor;

        impl<'de> serde::de::Visitor<'de> for StringVisitor {
            type Value = PkgWithArch;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("pkg with arch")
            }

            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                PkgWithArch::from_str(v).map_err(E::custom)
            }
        }

        deserializer.deserialize_str(StringVisitor)
    }
}

impl Display for PkgWithArch {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}@{}", self.pkg, self.arch)
    }
}

impl FromStr for PkgWithArch {
    type Err = PkgWithArchParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let (pkg_str, arch_str) = s.split_once(PkgSpec::ARCH_PREFIX)
            .ok_or(PkgWithArchParseError::NoArch)?;
        let kind = Pkg::from_str(pkg_str)?;
        let arch = Arch::from_str(arch_str)
            .map_err(|_| PkgWithArchParseError::BadArch)?;
        Ok(PkgWithArch { pkg: kind, arch })
    }
}

#[cfg(test)]
mod test {
    use std::str::FromStr;

    use crate::{package::pkg_with_arch::{PkgWithArch, PkgWithArchParseError}, Arch, Pkg, PkgParseError};

    #[test]
    fn test_pkg_with_arch_from_str() {
        assert_eq!(
            PkgWithArch::from_str("foo-1.2.3@x86_64"),
            Ok(PkgWithArch {
                pkg: Pkg { name: "foo".to_string(), version: "1.2.3".parse().unwrap() },
                arch: Arch::X86_64,
            })
        );
        assert_eq!(
            PkgWithArch::from_str("foo-1.2.3"),
            Err(PkgWithArchParseError::NoArch)
        );
        assert_eq!(
            PkgWithArch::from_str("foo@aarch64"),
            Err(PkgWithArchParseError::BadPkg(PkgParseError::NoVersion))
        );
    }
}
